package HighConcurrency.Nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server {//服务器端
    public static void main(String[] args) throws IOException {
        //开启通道
        ServerSocketChannel ssc=ServerSocketChannel.open();
        //绑定端口
        ssc.bind(new InetSocketAddress(8090));
        ssc.configureBlocking(false);//设置非阻塞
        Selector selector=Selector.open();//开启过滤器
        ssc.register(selector, SelectionKey.OP_ACCEPT);//接收申请允许
        while (true)//如果服务器长时间开启
        {
            selector.select();//筛选无用链接
            Set<SelectionKey> set=selector.selectedKeys();
            Iterator it=set.iterator();
            while (it.hasNext())
            {
                SelectionKey key= (SelectionKey) it.next();
                if (key.isAcceptable())//接收
                {
                    ServerSocketChannel sscx=(ServerSocketChannel) key.channel();//取出对应通道
                    SocketChannel sc=sscx.accept();//接收
                    sc.configureBlocking(false);//非阻塞
                    //注册事件读写
                    //register后一次的会覆盖前一次的状态
                    sc.register(selector,SelectionKey.OP_READ+SelectionKey.OP_WRITE);//加、或、异或都可以
                }
                if (key.isWritable())
                {
                    SocketChannel sc=(SocketChannel) key.channel();//取出对应通道
                    ByteBuffer bb=ByteBuffer.wrap("hello".getBytes());//构建一个缓冲区
                    sc.write(bb);
                    sc.register(selector,key.interestOps()-SelectionKey.OP_WRITE);//减write、与read、异或write
                }
                if (key.isReadable())
                {
                    SocketChannel sc=(SocketChannel) key.channel();//取出对应通道
                    ByteBuffer bb=ByteBuffer.allocate(1024);//构建一个缓冲区
                    sc.read(bb);
                    byte[] b=bb.array();
                    System.out.println(new String(b,0,bb.position()));//转化？
                    sc.register(selector,key.interestOps()-SelectionKey.OP_READ);//减read、或write、异或read
                }
                it.remove();

            }

        }
        //接收
//        SocketChannel sc=ssc.accept();
//
//        while (sc == null)
//        {//重连
//            sc=ssc.accept();
//        }
//        ByteBuffer bb=ByteBuffer.allocate(1024);//构建一个缓冲区
//        sc.read(bb); //读取数据
//        //解析数据
//        byte[] b=bb.array();
//        System.out.println(new String(b,0,bb.position()));//转化？
//        ssc.close();//关流



    }
}
